﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Globalization;
using System.Security.Principal;

using _3DTools;

using SBPweb.Modules.Communication;
using SBPweb.Modules.Modularity;
using SBPweb.Modules.Smartparts;
using SBPweb.Modules.Logging;
using SBPweb.Security.Authorization;

using SBPweb.MediaCenter.Tools.WPF.Controls;
using SBPweb.MediaCenter.Tools.WPF.Extenders;
using SBPweb.MediaCenter.Tools.WPF.Helpers;
using SBPweb.MediaCenter.Tools.WPF.Resources;

using SBPweb.MediaCenter.Presentation.WPF.Controls;

using SBPweb.MediaCenter.Common.Services;

namespace SBPweb.MediaCenter.Presentation.WPF
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, IModuleHost
    {

        #region Private fields

        private IPrincipal principal;

        private MessageQueueBase messageQueue;
        private CarouselListViewer<CarouselMenu> mainMenu;
        private LayoutManager<SmartpartList> smartpartListView;
        //private ILayoutService layoutProvider;
        
        private static int timesPainted = 0;

        private static DateTime recentTime;

        #endregion

        #region Constructor logic

        public MainWindow()
        {
            InitializeServices();
            InitializeComponent();
            InitializeControls();
            InitializeHost();
        }

        #endregion

        #region Property accessors

        public ModuleHostType HostType
        {
            get
            {
                return ModuleHostType.WindowsPresentationFoundation;
            }
        }

        public ILogManager LogManager
        {
            get
            {
                return App.LogManager;
            }
        }

        public ModuleLoader ModuleLoader
        {
            get
            {
                return App.Loader;
            }
        }

        public IPrincipal SecurityPrincipal
        {
            get
            {
                throw new NotImplementedException();
            }
            protected internal set
            {
                principal = value;
            }
        }

        public MenuBase Menu
        {
            get
            {
                return mainMenu.List;
            }
        }

        public MessageQueueBase Messages
        {
            get
            {
                return messageQueue;
            }
        }

        public SmartpartListBase Smartparts
        {
            get
            {
                return smartpartListView.List;
            }
        }

        public ILayoutProvider LayoutProvider
        {
            get
            {
                return smartpartListView as ILayoutProvider;
            }
        }

        public MenuBase StatusBar
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public CultureInfo[] SupportedCultures
        {
            get
            {
                return App.SupportedCultures;
            }
        }

        public IPersistable ParentPersistable
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        public string PersistencyKey
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        #endregion

        #region Events

        public event EventHandler OnApplicationClosing;

        #endregion

        #region Methods

        public void InitializeHost()
        {
            this.Closed += new EventHandler(Window_Closed);
            
            /*
            this.Visible = false;

            pSplashForm = new SplashForm();
            pSplashForm.Show(this);
            */

            App.Loader.ModuleGroupLoaded += new EventHandler(Loader_ModuleGroupLoaded);
        }

        public void InitializeServices()
        {
            this.smartpartListView = new SmartpartListView(this);
            this.ModuleLoader.Services.Put<ILayoutService>(this.smartpartListView as ILayoutService);
        }

        public void InitializeControls()
        {
            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

            this.WindowState = WindowState.Maximized;
            this.WindowStyle = WindowStyle.None;
            
            mainMenu = new CarouselMenuView(this, menuBaseVisual, camPerspective);
            mainMenu.MeshPopulating += new CarouselListViewer<CarouselMenu>.MeshGeometryPopulationHandler(mainMenu_MeshPopulating);

            mainMenu.List.ItemAdded += new EventHandler<MenuEventArgs>(pMainMenu_OnAdded);
            mainMenu.List.ItemRemoved += new EventHandler<MenuEventArgs>(pMainMenu_OnRemoved);
            mainMenu.SelectedIndexChanged += new EventHandler(mainMenu_SelectedIndexChanged);
            mainMenu.IsInteractive = true;
            mainMenu.Radius = 5.0f;
            mainMenu.AnimationSpeed = TimeSpan.FromMilliseconds(500);

            smartpartListView.DropVisual = innerGrid;
            smartpartListView.AnimationSpeed = TimeSpan.FromMilliseconds(500);

            smartpartListView.List.ItemAdded += new EventHandler<SmartpartEventArgs>(pSmartpartList_OnAdded);
            smartpartListView.List.ItemRemoved += new EventHandler<SmartpartEventArgs>(pSmartpartList_OnRemoved);

            this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
        }

        public void SetCulture(CultureInfo ci)
        {
            throw new NotImplementedException();
        }

        #region Event handlers
        
        private void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            timesPainted++;
            if ((DateTime.Now - recentTime) > TimeSpan.FromSeconds(1))
            {
                lFPS.Content = "FPS: " + timesPainted;
                timesPainted = 0;
                recentTime = DateTime.Now;
            }
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            //if (GlassHelper.IsGlassAvailable())
            //{
            //    GlassHelper.ExtendGlassFrame(this, new Thickness(-1));
            //}
        }

        protected delegate void Loader_ModuleGroupLoadedHandler(object sender, EventArgs e);

        protected void Loader_ModuleGroupLoaded(object sender, EventArgs e)
        {
            /*
            pSplashForm.Hide();

            if (mMemoryRefreshIntervall >= 0)
            {
                MemoryManagement.MinimizeWorkingSets();
                MemoryManagement.IntervalInSeconds = mMemoryRefreshIntervall;
                MemoryManagement.Enabled = true;
                //MemoryManagement.Enabled = false;
                this.Activated += new EventHandler(MainForm_Activated);
            }
            */
            this.Activate();
            this.Show();
            smartpartListView.Initialize();
        }

        private void pSmartpartList_OnAdded(object sender, SmartpartEventArgs e)
        {
            if (e.Smartpart is UserControl)
            {
                //mainMenuStack.Children.Add(sp);
            }
        }

        private void pSmartpartList_OnRemoved(object sender, SmartpartEventArgs e)
        {
            if (e.Smartpart is UserControl)
            {
                //mainMenuStack.Children.Remove(e.Smartpart as UserControl);
            }
        }

        private void pMainMenu_OnAdded(object sender, MenuEventArgs e)
        {
            if (e.Menu is UserControl)
            {
                //carousel.Items.Add(e.Menu as UserControl);
            }
        }

        private void pMainMenu_OnRemoved(object sender, MenuEventArgs e)
        {
            if (e.Menu is UserControl)
            {
                //carousel.Items.Remove(e.Menu as UserControl);
            }
        }

        private void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                default:
                    break;
                case Key.Right:
                    mainMenu.SelectedIndex -= 1;
                    break;
                case Key.Left:
                    mainMenu.SelectedIndex += 1;
                    break;
                case Key.Escape:
                    this.Close();
                    break;
            }
        }

        private void mainMenu_SelectedIndexChanged(object sender, EventArgs e)
        {
            DependencyObject menu = mainMenu.List[mainMenu.SelectedIndex] as DependencyObject;
            if (menu == null)
            {
                return;
            }
            TagDictionary tag = TagDictionary.GetTag(menu);
            if (tag == null)
            {
                return;
            }
            Color bgColor = tag.Get<string, Color>("BackgroundColor");
            ColorAnimation anim = new ColorAnimation(bgColor, new Duration(TimeSpan.FromMilliseconds(1000)));
            if (outerGrid.Background == null)
            {
                outerGrid.Background = new SolidColorBrush(Colors.Transparent);
            }
            outerGrid.Background.BeginAnimation(SolidColorBrush.ColorProperty, anim);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (OnApplicationClosing != null)
            {
                OnApplicationClosing(this, e);
            }
            App.Current.Shutdown();
        }

        private void smartpartListView_MeshPopulating(object sender, out Geometry3D geometry)
        {
            geometry = (this.TryFindResource("PlaneMesh") as Geometry3D).Clone();
        }

        private void mainMenu_MeshPopulating(object sender, out Geometry3D geometry)
        {
            geometry = (this.TryFindResource("PlaneMesh") as Geometry3D).Clone();
        }

        #endregion


        #endregion

    }
    /*
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, IModuleHost
    {

        #region Private fields

        private IMenuList pMainMenu;
        private IMessageQueue pMessageQueue;
        private SmartpartListBase pSmartpartList;

        #endregion

        #region Constructor logic

        public MainWindow()
        {
            InitializeComponent();

            pMainMenu = new CarouselMenu();
            pSmartpartList = new SmartpartList();

            pMainMenu.ItemAdded += new EventHandler<MenuEventArgs>(pMainMenu_OnAdded);
            pMainMenu.ItemRemoved += new EventHandler<MenuEventArgs>(pMainMenu_OnRemoved);

            pSmartpartList.ItemAdded += new EventHandler<SmartpartEventArgs>(pSmartpartList_OnAdded);
            pSmartpartList.ItemRemoved += new EventHandler<SmartpartEventArgs>(pSmartpartList_OnRemoved);

            this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
        }

        #endregion

        void pSmartpartList_OnAdded(object sender, SmartpartEventArgs e)
        {
            if (e.Smartpart is UserControl)
            {
                //carousel.Items.Add(e.SmartPart as UserControl);
            }
        }

        void pSmartpartList_OnRemoved(object sender, SmartpartEventArgs e)
        {

        }

        void pMainMenu_OnAdded(object sender, MenuEventArgs e)
        {
            if (e.Menu is UserControl)
            {
                //carousel.Items.Add(e.Menu as UserControl);
            }
        }

        void pMainMenu_OnRemoved(object sender, MenuEventArgs e)
        {
            if (e.Menu is UserControl)
            {
                //carousel.Items.Remove(e.Menu as UserControl);
            }
        }

        void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            //switch (e.Key)
            //{
            //    default:
            //        break;
            //    case Key.Up:
            //        if (carousel.Index != 0)
            //        {
            //            carousel.Index -= 1;
            //        }
            //        break;
            //    case Key.Down:
            //        if (carousel.Index < carousel.Items.Count - 1)
            //        {
            //            carousel.Index += 1;
            //        }
            //        break;
            //}
        }

        #region IModuleHost Members

        public IMenuList Menu
        {
            get
            {
                return pMainMenu;
            }
        }

        public IMessageQueue Messages
        {
            get
            {
                return pMessageQueue;
            }
        }

        public SmartpartListBase Smartparts
        {
            get
            {
                return pSmartpartList;
            }
        }

        #endregion

        #region IModuleHost Members

        public ModuleHostType HostType
        {
            get { throw new NotImplementedException(); }
        }

        public ILayoutProvider LayoutProvider
        {
            get { throw new NotImplementedException(); }
        }

        public SBPweb.Modules.Logging.ILogManager LogManager
        {
            get { throw new NotImplementedException(); }
        }

        public ModuleLoader ModuleLoader
        {
            get { throw new NotImplementedException(); }
        }

        public event EventHandler OnApplicationClosing;

        public System.Security.Principal.IPrincipal SecurityPrincipal
        {
            get { throw new NotImplementedException(); }
        }

        public void SetCulture(System.Globalization.CultureInfo ci)
        {
            throw new NotImplementedException();
        }

        public IMenuList StatusBar
        {
            get { throw new NotImplementedException(); }
        }

        public System.Globalization.CultureInfo[] SupportedCultures
        {
            get { throw new NotImplementedException(); }
        }

        #endregion

        #region IPersistable Members

        public IPersistable ParentPersistable
        {
            get { throw new NotImplementedException(); }
        }

        public string PersistencyKey
        {
            get { throw new NotImplementedException(); }
        }

        #endregion
    }
    */

}
